import moment from 'moment'

export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome() {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader(callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    (event) => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE() {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * 过滤对象中为空的属性
 * @param obj
 * @returns {*}
 */
export function filterObj(obj) {
  if (!(typeof obj == 'object')) {
    return
  }

  for (let key in obj) {
    if (obj.hasOwnProperty(key) && (obj[key] == null || obj[key] == undefined || obj[key] === '')) {
      delete obj[key]
    }
  }
  return obj
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}
export function scorePassword(pass) {
  let score = 0
  if (!pass) {
    return score
  }
  // award every unique letter until 5 repetitions
  const letters = {}
  for (let i = 0; i < pass.length; i++) {
    letters[pass[i]] = (letters[pass[i]] || 0) + 1
    score += 5.0 / letters[pass[i]]
  }

  // bonus points for mixing it up
  const variations = {
    digits: /\d/.test(pass),
    lower: /[a-z]/.test(pass),
    upper: /[A-Z]/.test(pass),
    nonWords: /\W/.test(pass),
  }

  let variationCount = 0
  for (var check in variations) {
    variationCount += variations[check] === true ? 1 : 0
  }
  score += (variationCount - 1) * 10

  return parseInt(score)
}


export function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

// 图片资源格式转换
export function imagesList(imgList){
  if(!imgList || !imgList.length){
    return []
  }
  return imgList?.map((item, index) => {
    const eq = index+1;
    if (item.url) {
      return {
        sort: eq,
        // confId: item.confId,
        url: item.url,
      }
    } else {
      return {
        sort: eq,
        // confId: item.response.data.id,
        url: item.response.data.fileName,
      }
    }
  });
}

// 数据新增千分符
export const numFormat = (num) => {
  let firstStr = String(num).startsWith('-') ? String(num).slice(0, 1) : '' // 判断这个数字是不是负数
  num = firstStr ? String(num).slice(1) : String(num) // 如果是负数就截取掉负数 再进行千分符的添加
  num = num.split('.') // 分隔小数点
  let arr = num[0].split('').reverse() // 转换成字符数组并且倒序排列
  let res = []
  for (let i = 0, len = arr.length; i < len; i++) {
    if (i % 3 === 0 && i !== 0) {
      res.push(',') // 添加分隔符
    }
    res.push(arr[i])
  }
  res.reverse() // 再次倒序成为正确的顺序
  if (num[1]) {
    // 如果有小数的话添加小数部分
    res = res.join('').concat(`.${num[1]}`)
  } else {
    res = res.join('')
  }
  return firstStr ? `${firstStr}${res}` : res // 判断如果有负号，最后再添加到首位
}

export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    let part = encodeURIComponent(propName) + "=";
    if (value !== null && typeof(value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          let params = propName + '[' + key + ']';
          const subPart = encodeURIComponent(params) + "=";
          result += subPart + encodeURIComponent(value[key]) + "&";
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}

// 自然数
export const numberNatural = (value , intLength = 1) => {
  return value?.trim().replace(/^.*?(0|[1-9]\d*)?.*?$/g,(...args) => args[1] || '');
}

/** 0- 9{n}.99 保留两位小数 */
export const limitNumberLength  = (value, intLength= 10) => {
  const max = intLength - 1;
  const reg = new RegExp(`^.*?((?:0|[1-9]${max <= 0 ? '' : `\\d{0,${max}}`})(?:\\.\\d{0,2})?)?.*?$`,'g');
  return value?.trim().replace(reg,(...args) => args[1] || '');
}

// 数组根据某个字段排序
export const compare = (property) => {
  return function (a, b) {
    const value1 = a[property];
    const value2 = b[property];
    return value1 - value2;
  }
}

export function copyToClipboard (text) {
  if (!document.createRange || !window.getSelection || !document.execCommand) {
    return false;
  }
  const node = document.createElement('span');
  node.innerText = text;
  document.body.appendChild(node);
  const range = document.createRange();
  range.selectNode(node);
  const selection = window.getSelection();
  selection.empty();
  selection.addRange(range);
  document.execCommand('copy');

  selection.empty();
  range.detach();
  document.body.removeChild(node);

  return true;
}

// 时间日期选择
export const timeRangs = {
  '1周': [moment().startOf('day').subtract(1, 'weeks'), moment()],
  半个月: [moment().startOf('day').subtract(14, 'days'), moment()],
  '3个月': [moment().startOf('day').subtract(3, 'months'), moment()],
  '6个月': [moment().startOf('day').subtract(6, 'months'), moment()],
  '1年': [moment().startOf('day').subtract(1, 'years'), moment()],
}

// 权限树改写数据格式 menuResponseList 就是child
export function mapTree(org) {
  const childs = Array.isArray(org.menuResponseList) && org.menuResponseList.length > 0;
  return {
    ...org,
    text: org.title,
    title: org.permissionName,
    key: org.permissionId,
    value: org.permissionId,
    children: childs ? org.menuResponseList.map((r) => mapTree(r)) : undefined,
  };
}


export function getAllIds(tree, result) {
  //遍历树  获取id数组
  for (const i in tree) {
    result.push(tree[i].permissionId); // 遍历项目满足条件后的操作
    if (tree[i].menuResponseList) {
      //存在子节点就递归
      getAllIds(tree[i].menuResponseList, result);
    }
  }
  return result;
}

// 菜单权限展开
export function getMenuList(tree, result) {
  //遍历树  获取id数组
  for (const i in tree) {
    result.push(tree[i]); // 遍历项目满足条件后的操作
    if (tree[i].menuResponseList) {
      //存在子节点就递归
      getMenuList(tree[i].menuResponseList, result);
    }
  }
  return result;
}

export function filterSpecialCharacters() {
  var regex = /[^\w\s]/gi; // 定义要过滤的特殊字符规则
  return str.replace(/[^\w\s]/gi, ''); // 将所有匹配到的特殊字符替换为空字符串
}

// 判断是否是生产和测试环境
export const isPro =  process.env.NODE_ENV === 'production';
export const isDev =  process.env.NODE_ENV !== 'production';

